/**
 * 索引所有组件, 生成index.js文件
 * 收集所有主题样式, 生成components-themes.scss文件
 */
const fs=require('fs/promises');
const chalk=require('chalk');
const {camelCase,upperFirst}=require('lodash');

/**
 * 索引出主题对象themes
 */
function index(path,themes){
	return fs.readdir(path,{withFileTypes:true}).then((dirs) => {
		const components=dirs.filter((dir) => {
			return dir.isDirectory();
		});
		let jsFileStr='';
		const buildThemesPromise=[];
		for(let i=0;i<components.length;++i){
			const name=components[i].name;
			const componentName=upperFirst(camelCase(name));
			const styleDir=`${path}/${name}/style`;
			jsFileStr+=`export {default as ${componentName}} from './${name}';\n`;
			buildThemesPromise.push(fs.readdir(styleDir).then((dirs) => {
				for(let j=0;j<dirs.length;++j){
					const theme=dirs[j];
					if(themes[theme]==null){
						themes[theme]={};
					}
					themes[theme][componentName]=`\n\t\t//${componentName}\n\t\t@import "${styleDir}/${theme}/index";`;
				}
			}).catch(function(){}));
		}
		buildThemesPromise.push(fs.writeFile(path+'/index.ts',jsFileStr));
		return Promise.all(buildThemesPromise);
	});
}
/**
 * 生成平台对应的css字符串
 */
function getPlatformStyle(themes,platformName){
	let platformStyle=`.${platformName}{`;
	const themeNames=Object.keys(themes).sort();
	for(let i=0;i<themeNames.length;++i){
		const themeName=themeNames[i];
		let themeStyle=`\n\t&.${themeName}-theme{`;
		const theme=themes[themeName];
		const componentNames=Object.keys(theme).sort();
		for(let j=0;j<componentNames.length;++j){
			const componentName=componentNames[j];
			themeStyle+=theme[componentName];
		}
		platformStyle+=themeStyle+'\n\t}';
	}
	return platformStyle+'\n}\n';
}
const pcThemes={};
const appThemes={};
fs.rm('doc/components-themes.scss',{force:true}).then(() => {
	return Promise.all([
		index('src/components/pc',pcThemes),
		index('src/components/app',appThemes),
	]);
}).then(() => {
	return fs.writeFile(
		'doc/components-themes.scss',
		getPlatformStyle(pcThemes,'pc-platform')+
		getPlatformStyle(appThemes,'app-platform')
	);
}).then(() => {
	console.log(chalk.green('索引库成功!'));
}).catch(() => {
	console.log(chalk.red('索引库失败!'));
});
